<?php

namespace App\Model;

use App\BaseModel;
use App\Helpers\Helpers;

class Order extends BaseModel
{
    protected $table = "orders";

    protected $appends = ["chState","overtime",'giftUrl','expressStatus','chExpressStatus'];

    protected $orderState = [
        0 => '待支付',
        1 => '待发货',
        2 => '已取消',
        3 => '未领取',
        4 => '已过期',
        5 => '已发货',
        6 => '已完成',
        7 => '已关闭',
        8 => '已领取待使用',
        9 => '已过期退款中',
        10 => '已过期已退款'
    ];

    //创建人
    public function createUser()
    {
        return $this->belongsTo('App\User','create_user_id','id');
    }

    //接收人
    public function getUser()
    {
        return $this->belongsTo('App\User','get_user_id','id');
    }

    //产品
    public function product()
    {
        return $this->belongsTo('App\Model\WineProduct','product_id','id');
    }

    //支付记录
    public function payRecord()
    {
        return $this->hasOne('App\Model\OrderPayRecord','order_id','id')
            ->orderBy('order_pay_records.created_at','desc');
    }
    //二维码记录
    public function qrcodeRecord()
    {
        return $this->hasOne('App\Model\WineQrcodeRecord','code','origin_qrcode');
    }
    //物流记录
    public function express()
    {
        return $this->hasOne('App\Model\Express','out_trade_no','out_trade_no');
    }
    //优惠券
    public function coupon()
    {
        return $this->hasOne('App\Model\UserCoupon','order_id','id');
    }

    public function importer()
    {
        return $this->hasOne('App\Model\Importer','id','importer_id');
    }
    //状态（中文）
    public function getChStateAttribute()
    {
        return isset($this->orderState[$this->state])?$this->orderState[$this->state]:$this->state;
    }

    //到期时间
    public function getOvertimeAttribute()
    {
        if ($e = $this->expire_time){
            return date('Y.m.d H:i');
            //return Helpers::SYSJ(strtotime($e));
        }
        return null;
    }

    //物流状态
    public function getExpressStatusAttribute()
    {
        return $this->express?$this->express->status:null;
    }

    //物流状态(中文)
    public function getChExpressStatusAttribute()
    {
        return $this->express?$this->express->ChStatus:null;
    }

    //not used
    public static function checkExist($product_id,$user_id,$type,$quantity)
    {
        $orders = Order::where('product_id','=',$product_id)
            ->where('type','=',$type)
            ->where('quantity','=',$quantity)
            ->where('user_id','=',$user_id)
            ->where('state','=',0)
            ->get();
        return $orders;
    }

    //添加地址信息
    public function addAddressInfo($address_id,$user_id)
    {
        $address = UserAddress::find($address_id);
        $this->get_user_id = $user_id;
        $this->username = $address->userName;
        $this->tel_number = $address->telNumber;
        $this->address = $address->complete_address;
        $this->save();
    }

    //生成具有signCode的GiftUrlParam
    public static function createGiftCompleteUrl($order,$timestamp)
    {
        $param = self::createGiftUrlParam($order,$timestamp);
        $signCode = self::createGiftUrlParamSingCode($param,$order->out_trade_no,$timestamp);
        return $param.'&signCode='.$signCode;
    }

    //检测有效性
    public static function checkGiftUrlParam($order,$timestamp,$signCode)
    {
        $param = self::createGiftUrlParam($order,$timestamp);
        $code = self::createGiftUrlParamSingCode($param,$order->out_trade_no,$timestamp);

        return $signCode == $signCode;

    }

    //生成SingCode
    public static function createGiftUrlParamSingCode($param,$out_trade_no,$timestamp)
    {
        return md5($param.'&out_trade_no='.$out_trade_no.'&timestamp='.$timestamp);
    }

    //生成GiftUrlParam
    public static function createGiftUrlParam($order,$timestamp)
    {
        return 'giftCode='.$order->md5_out_trade_no.'&expire_time='.strtotime($order->expire_time).'&timestamp='.$timestamp;
    }

    //根据订单号查找订单
    public static function findByOutTradeNo($out_trade_no)
    {
        return self::where('out_trade_no','=',$out_trade_no)->first();
    }

    //礼物获取url
    public function getGiftUrlAttribute()
    {
        if ($this->type == "gift" && $this->state == 3){
            return self::createGiftCompleteUrl($this,time());
        }
        return null;
    }

    //单个订单商品回库
    public static function skuReturnBySinge($order)
    {
        if ($order->state == 0) {
            //订单关闭
            $order->state = 7;
            $order->save();

            if($product = $order->product) {
                $product->sku += $order->quantity;
                return $product->save();
            }
        }
        return false;
    }
}
